package com.haoshuang.zhouzhoubang.ui.page.mine.recognizance.pay.preview

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import androidx.recyclerview.widget.LinearLayoutManager
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.ActivityUtils
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.config.Config
import com.haoshuang.zhouzhoubang.config.URLConstants
import com.haoshuang.zhouzhoubang.databinding.ActivityPreviewPayDepositBinding
import com.haoshuang.zhouzhoubang.model.bean.BzjData
import com.haoshuang.zhouzhoubang.ui.activity.BondTdNewActivity
import com.haoshuang.zhouzhoubang.ui.page.help.detail.HelpDetailActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.recognizance.one.RecognizancePayOneActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.recognizance.pay.success.SuccessActivity9
import com.haoshuang.zhouzhoubang.utils.Event
import com.haoshuang.zhouzhoubang.utils.PayResult
import com.haoshuang.zhouzhoubang.utils.PaymentUtil
import com.haoshuang.zhouzhoubang.utils.PreferenceUtils
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.getString
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.DecimalFormat

/**
 *
 */
class PreviewPayDepositActivity :
    BaseVMActivity<PreviewPayDepositViewModel, ActivityPreviewPayDepositBinding>() {

    companion object {
        fun launch(context: Context) {
            context.startPage<PreviewPayDepositActivity>()
        }
    }

    private var bean: BzjData.PayCategory? = null
    var list = arrayListOf<BzjData.PayCategory>()

    lateinit var adapter: BondTdAdapter55
    var pay_type = 1

    // 服务分类id
    private var service_id = ""

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        bean = intent.getSerializableExtra("bean") as BzjData.PayCategory?
        binding.titleBar.title = "保证金缴纳"
        binding.titleBar.leftImageView().click { finish() }
        service_id = intent.getString("service_id")
        binding.apply {
            rvList.layoutManager = LinearLayoutManager(mActivity)
            adapter = BondTdAdapter55(list)
            rvList.adapter = adapter
            tvBzj.clickWithTrigger {
                var url = "${URLConstants.baseUrl}/index/index/agreement?id=9"
                startPage<HelpDetailActivity>("title" to "保证金规则", "url" to url)
            }
            llWx.clickWithTrigger {
                ivWx.setImageResource(R.mipmap.dz_ok)
                ivZfb.setImageResource(R.mipmap.dz_wx)
                pay_type = 1
            }
            llZfb.clickWithTrigger {
                ivWx.setImageResource(R.mipmap.dz_wx)
                ivZfb.setImageResource(R.mipmap.dz_ok)
                pay_type = 2
            }
            tvNext.clickWithTrigger {
                var service_id = ""
                for (b in list) {
                    service_id = service_id + b.id + ","
                }

                if (pay_type == 1) {
                    vm.getData3(
                        "service_id" to service_id.substring(0, service_id.length - 1),
                        "pay_type" to pay_type,
                        "id" to team_id,
                        "state" to 0,
                        "type" to 2,
                        "order_amount" to order_amount
                    )
                } else {
                    vm.getData2(
                        "service_id" to service_id.substring(0, service_id.length - 1),
                        "pay_type" to pay_type,
                        "id" to team_id,
                        "state" to 0,
                        "type" to 2,
                        "order_amount" to order_amount
                    )
                }

            }
        }
    }

    var ids = 0
    var order_amount = ""
    override fun initData() {
        vm.getData1( "cate_id" to service_id)
        vm.getData()
    }

    private val SDK_PAY_FLAG = 1
    fun payAlipay(mContext: Context?, orderNo: String) {
        val payRunnable = Runnable {
            val alipay = PayTask(mContext as Activity?)
            val result = alipay.payV2(orderNo, true)
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }
        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    @SuppressLint("HandlerLeak")
    var mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)


                    val resultInfo = payResult.result
                    val resultStatus = payResult.resultStatus

                    if (TextUtils.equals(resultStatus, "9000")) {
                        if (ActivityUtils.isActivityExistsInStack(BondTdNewActivity::class.java)) {
                            ActivityUtils.finishActivity(BondTdNewActivity::class.java)
                        }
                        if (ActivityUtils.isActivityExistsInStack(RecognizancePayOneActivity::class.java)) {
                            ActivityUtils.finishActivity(RecognizancePayOneActivity::class.java)
                        }
                        toast("支付成功")
                        startPage<SuccessActivity9>()
                        finish()
                    } else {
                        toast("支付失败")
                    }
                }

                else -> {}
            }
        }
    }

    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageEvent: Event) {

        if (messageEvent.code == 80114) {
            if (ActivityUtils.isActivityExistsInStack(BondTdNewActivity::class.java)) {
                ActivityUtils.finishActivity(BondTdNewActivity::class.java)
            }
            if (ActivityUtils.isActivityExistsInStack(RecognizancePayOneActivity::class.java)) {
                ActivityUtils.finishActivity(RecognizancePayOneActivity::class.java)
            }
            toast("支付成功")
            startPage<SuccessActivity9>()
            finish()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun startObserve() {
        vm.getData3.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                var api = WXAPIFactory.createWXAPI(mActivity, Config.WX_ID, false)
                PreferenceUtils.putString("Wxpay", "8")
                PaymentUtil.payWxPayment(api, it)
            }
        }
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                payAlipay(mActivity, it?.body!!)
            }
        }
        vm.getData1.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    list.clear()
                    var order_amount22 = 0.0
                    for (b in it.not_pay_category.filter { it.id == bean?.id }) {
                        order_amount22 += b.team_money.toDouble()
                    }
                    order_amount = order_amount22.toString()
                    val df = DecimalFormat("#0.00")
                    var order_amount2 = df.format(order_amount22)
                    binding.allPrice.setText("¥${order_amount2}")
                    list.addAll(it.not_pay_category.filter { it.id == bean?.id })
                    adapter.notifyDataSetChanged()
                }

            }
        }
    }

}